<template>
  <div style="width:100%; text-align: center" >
    <a-form-model
      :model="user"
      :rules="formRules"
      ref="formRef"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :style="{'margin': '40px auto 0'}"
    >
      <a-form-model-item :label="$t('all.autotext717')" prop="pwd">
        <a-input-password v-model="user.pwd" :placeholder="$t('all.autotext1261')" />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext168')" prop="pwdConfirm">
        <a-input-password v-model="user.pwdConfirm" :placeholder="$t('all.autotext1261')" />
      </a-form-model-item>
      <div style="display:flex;justify-content:center">
        <a-button
          :loading="btnLoading"
          type="primary"
          style="width:100px"
          @click="nextStep"
        >
          {{ $t('all.autotext792') }}
        </a-button>
      </div>
    </a-form-model>
  </div>
</template>
<script>
import { updatePassword } from '@/api/system/user'
import storage from 'store'
import { ACCESS_TOKEN_TEMP } from '@/store/mutation-types'

export default {
  data () {
    const validatorConfirmPwd = (rule, value, callback) => {
      if (this.user.pwd === this.user.pwdConfirm) {
        callback()
      } else {
        callback(new Error(this.$t('all.autotext1099')))
      }
    }
    return {
      btnLoading: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 9 },
      user: {
        pwd: '',
        pwdConfirm: ''
      },
      formRules: {
        pwd: [
          { required: true, message: this.$t('all.autotext734'), trigger: 'change' },
          // { pattern: /^[^\u4e00-\u9fa5]{8,}$/, message: '至少为8位包含数字、英文字母、特殊符号组合' }
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: this.$t('all.autotext1261') }
        ],
        pwdConfirm: [
          { required: true, message: this.$t('all.autotext118'), trigger: 'change' },
          // { pattern: /^[^\u4e00-\u9fa5]{8,}$/, message: '至少为8位包含数字、英文字母、特殊符号组合' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: this.$t('all.autotext1261') },
          { required: true, trigger: 'change', validator: validatorConfirmPwd }
        ]
      }
    }
  },
  methods: {
    nextStep () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.updatePassword()
        }
      })
    },
    updatePassword () {
      this.btnLoading = true
      updatePassword({ pwd: this.user.pwd })
        .then(res => {
          this.btnLoading = false
          this.$message.success(this.$t('all.autotext1020'))
          storage.remove(ACCESS_TOKEN_TEMP)
          // 清空权限
          this.$store.dispatch('Logout', 1).then(() => {
            this.$router.push({ name: 'login' })
          })
        })
        .catch(() => {
          this.btnLoading = false
        })
    }
  }
}
</script>
